package pyip.lib.mixtool.chineseconverter;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 根据 java-zhconverter 修改而来
 * https://code.google.com/p/java-zhconverter/ 
 * @author yepeng
 * @date 2014年12月25日
 */
public class ChineseConverter {

    private static final Logger logger = LoggerFactory.getLogger(ChineseConverter.class);

    private Properties charMap = new Properties();
    private Set<String> conflictingSets = new HashSet<>();

    public static final int TRADITIONAL = 0;
    public static final int SIMPLIFIED = 1;
    private static final int NUM_OF_CONVERTERS = 2;
    private static final ChineseConverter[] converters = new ChineseConverter[NUM_OF_CONVERTERS];
    private static final String[] propertyFiles = new String[2];

    static {
        propertyFiles[TRADITIONAL] = "chineseconverter/zh2traditional.properties";
        propertyFiles[SIMPLIFIED] = "chineseconverter/zh2simplified.properties";
    }

    /**
     * @param converterType 0 for traditional and 1 for simplified
     * @return
     * @throws IOException maybe throws when the first time call with same params
     */
    public static ChineseConverter getInstance(int converterType) throws IOException {

        if (converterType >= 0 && converterType < NUM_OF_CONVERTERS) {

            if (converters[converterType] == null) {
                synchronized (ChineseConverter.class) {
                    if (converters[converterType] == null) {
                        converters[converterType] = new ChineseConverter(propertyFiles[converterType]);
                    }
                }
            }
            return converters[converterType];

        } else {
            return null;
        }
    }

    public static String convert(String text, int converterType) throws IOException {
        ChineseConverter instance = getInstance(converterType);
        return instance.convert(text);
    }

    private ChineseConverter(String propertyFile) throws IOException {
//        InputStream is = getClass().getResourceAsStream(propertyFile);
        InputStream is = ChineseConverter.class.getClassLoader().getResourceAsStream(propertyFile);
        if (is == null) {
            throw new FileNotFoundException("mapping file '" + propertyFile + "' not found");
        }

        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(is));
            charMap.load(reader);
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                logger.error("close stream exception after read file '" + propertyFile + " '", e);
            }
        }
        initializeHelper();
    }

    public static void main(String[] args) throws IOException {
        ChineseConverter converter = ChineseConverter.getInstance(ChineseConverter.SIMPLIFIED);
        System.out.println(converter.convert("有背光的機械式鍵盤"));
        System.out.println(converter.convertOneChar('盤'));
    }

    private void initializeHelper() {
        Map<String, Integer> stringPossibilities = new HashMap<>();
        @SuppressWarnings("rawtypes")
        Iterator iter = charMap.keySet().iterator();
        while (iter.hasNext()) {
            String key = (String) iter.next();
            if (key.length() >= 1) {
                for (int i = 0; i < (key.length()); i++) {
                    String keySubstring = key.substring(0, i + 1);
                    if (stringPossibilities.containsKey(keySubstring)) {
                        stringPossibilities.put(keySubstring, stringPossibilities.get(keySubstring) + 1);
                    } else {
                        stringPossibilities.put(keySubstring, 1);
                    }

                }
            }
        }

        iter = stringPossibilities.keySet().iterator();
        while (iter.hasNext()) {
            String key = (String) iter.next();
            if (stringPossibilities.get(key) > 1) {
                conflictingSets.add(key);
            }
        }
    }

    public String convert(String in) {
        StringBuilder outString = new StringBuilder();
        StringBuilder stackString = new StringBuilder();

        for (int i = 0; i < in.length(); i++) {

            char c = in.charAt(i);
            String key = "" + c;
            stackString.append(key);

            if (conflictingSets.contains(stackString.toString())) {
            } else if (charMap.containsKey(stackString.toString())) {
                outString.append(charMap.get(stackString.toString()));
                stackString.setLength(0);
            } else {
                CharSequence sequence = stackString.subSequence(0, stackString.length() - 1);
                stackString.delete(0, stackString.length() - 1);
                flushStack(outString, new StringBuilder(sequence));
            }
        }

        flushStack(outString, stackString);

        return outString.toString();
    }

    private void flushStack(StringBuilder outString, StringBuilder stackString) {
        while (stackString.length() > 0) {
            if (charMap.containsKey(stackString.toString())) {
                outString.append(charMap.get(stackString.toString()));
                stackString.setLength(0);
            } else {
                outString.append("" + stackString.charAt(0));
                stackString.delete(0, 1);
            }

        }
    }

    public String convertOneChar(char c) {
        String s = c + "";
        if (charMap.containsKey(s)) {
            return (String) charMap.get(s);
        }
        return s;
    }

}
